<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-button type="primary" size="default" @click="addTrademark" :icon="Plus">添加</el-button>
        </template>
        <el-table style="margin-bottom: 30px" :data="tabelData" border stripe>
            <el-table-column label="序号" align="center" type="index" width="80" />
            <el-table-column label="品牌名称" prop="tmName"></el-table-column>
            <el-table-column label="品牌LOGO" prop="logUrl">
              <template #default="{ row }">
                <img height="60" :src="row.logoUrl" alt="" />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="warning" size="small" @click="updateTrademark(row)" :icon="Edit">修改</el-button>
                <el-button type="danger" size="small" @click="deleteTrademark(row.id)" :icon="Delete">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
        <el-pagination
                v-model:page-size="limit"
                v-model:current-page="page"
                :pager-count="5"
                :page-sizes="[3, 5, 7, 9]"
                layout="prev, pager, next,sizes,total"
                :total="total"
            >
        </el-pagination>
    </el-card>
  <el-dialog v-model="dialogFormVisible" :title="newTrademark.id?'修改品牌':'添加品牌'">
    <el-form label-width="100px" :model="newTrademark" :rules="trademarkRules" ref="ruleFormRef">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input  autocomplete="off"  v-model="newTrademark.tmName"/>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="`${baseUrl}/admin/product/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrAddTrademark"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Trademark",
});
</script>

<script setup lang="ts">
    import { Plus,Edit, Delete } from '@element-plus/icons-vue'
    import {ref, toRefs,onMounted, watch,reactive } from 'vue'
    import { requestTrademarkList ,requestAddTrademark,requestUpdateTrademark,requestDeleteTrademark} from "@/api/trademark";
    import type { reqTrademarkReturnRecordsType ,reqTrademarkReturnItemType} from "@/api/trademark";
    import { ElMessage ,ElMessageBox} from 'element-plus'
    import type { UploadProps , FormRules , FormInstance} from 'element-plus'

   
    //1.table的逻辑
    //table数据
    const tabelData = ref<reqTrademarkReturnRecordsType>([]);

    //2.页码逻辑
    //页码的数据和类型
    interface pageDateType {
        page: number;
        limit: number;
        total: number;
    }
    const pageDate = ref<pageDateType>({
        page: 1,
        limit: 3,
        total: 80,
    });
    //解构出页码的属性
    const { page, limit, total } = toRefs(pageDate.value);

    //监听页码的改变 然后重新发送请求
watch([page, limit], () => {
  getTrademarkList();
});

//3.获取品牌列表
//封装获取品牌列表的功能函数
const getTrademarkList = async () => {
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value,
  });

  //把请求回来的值设置给响应数据
  tabelData.value = result.records;
  total.value = result.total;
};
//初始化
onMounted(() => {
  //调用获取品牌列表的功能函数
  getTrademarkList();
});
/*
//最完成的解构ref属性的带类型的写法
  const {
    page,
    limit,
    total,
  }: { page: Ref<number>; limit: Ref<number>; total: Ref<number> } =
    toRefs<pageDateType>(pageDate.value);

  //对象解构如何限制类型(一般不会限制,因为都能推断出来)
  const o = { a: 1, b: 2 };
  const { a, b }: { a: number; b: number } = o;
  console.log(a, b);
*/

//控制弹窗的显示与隐藏
const dialogFormVisible = ref(false)
const baseUrl = import.meta.env.VITE_API_URL
const newTrademark = ref<reqTrademarkReturnItemType>({
  logoUrl:'',
  tmName:'',
  id:0
})

//4.图片上传逻辑
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  newTrademark.value.logoUrl = response.data
  // console.log(imageUrl.value,response);
  
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//自定义表单校验
const validatePass = (rule: any, value: string, callback: any) => {
  if (value.length < 2 || value.length > 5) {
    callback('长度是2-5')
  } else if(!value.trim()){
    callback('不能为空')
  }else{
    callback()
  }
}
//5. 点击添加
const addTrademark = () => {
  //清空以前的表单验证
  ruleFormRef.value?.clearValidate()
  dialogFormVisible.value = true
  //清空以前的信息，点击修改时双向绑定留下的
  newTrademark.value = {
    tmName:'',
    logoUrl:'',
    id:0
  }
}

//6.点击修改
const updateTrademark = (row:reqTrademarkReturnItemType) => {
  //清空以前的表单验证
  ruleFormRef.value?.clearValidate()
  dialogFormVisible.value = true
  //因为数据双向绑定，直接把现在点击的品牌信息赋值给newTrademark
  //因为row对象引用地址一样，所以不能直接赋值，需要浅拷贝
  newTrademark.value = {...row}
}

//表单实例
const ruleFormRef = ref<FormInstance>()
//7.添加或修改品牌
const updateOrAddTrademark = async () => {
  try {  
      await ruleFormRef.value?.validate()
      //先关闭弹窗
      dialogFormVisible.value = false
      try{
          //因为添加品牌没有id，修改品牌有id，所以判断有无id，发不同请求
        if(newTrademark.value.id){
          await requestUpdateTrademark(newTrademark.value)
          ElMessage.success('修改成功')
        }else{
          await requestAddTrademark(newTrademark.value)
          ElMessage.success('添加成功')
          //跳回首页
          page.value = 1
        }
           //重新获取列表
        getTrademarkList()
      }catch(e){
        ElMessage.error(newTrademark.value.id?'修改失败':'添加失败')
      }
    } catch (e) {
      e;
    }
}

//8.删除逻辑
const deleteTrademark = (id:number) => {
  ElMessageBox.confirm('真的要删除吗？',"警告！！！",{
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        await requestDeleteTrademark(id)
        ElMessage.success('删除成功')
        //重新获取列表
        getTrademarkList()
      } catch (e) {
        ElMessage.error('删除失败')
      }
    }).catch(() => {
      ElMessage.info('点错了吗？')
    }) 
}
//表单校验
const trademarkRules = reactive<FormRules>({
      tmName:[
        { required: true, message: '必须填写品牌名称', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' },
      ],
      logoUrl:[
        { required: true, message: '必须上传图片', trigger: 'blur' }
      ]
  })
</script>

 <style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>